//
//  HomeTableViewController.swift
//  01weiboSwift
//
//  Created by 龚欣 on 15/6/24.
//  Copyright © 2015年 gong. All rights reserved.
//

import UIKit
import SVProgressHUD
import SDWebImage

let statusNormalReuserCellIdentifier = "statusNormalReuserCellIdentifier"
let statusForwardReuserCellIdentifier = "statusForwardReuserCellIdentifier"

class HomeTableViewController: BaseTableViewController,statusCellDelegate {

    var homeStatuses : [Status]?  {
        didSet{
            tableView.reloadData()
            
        }
    }
    
    var rowHeightCache = [Int : CGFloat]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if !isLogin{
            return
        }

        setUpNavigationBar()
        setUpTableView()
        preferRefreshView()
    }
    
    override func didReceiveMemoryWarning() {
        rowHeightCache.removeAll()
    }
    // MARK: 准备刷新的控件
    private func preferRefreshView(){
    
        refreshControl = HomeStatusRefresh() as HomeStatusRefresh
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
        loadData()
    }
    /// 上拉刷新的标记，用来修改是发送下拉刷新的请求还是上拉刷新修改的值
    var pullRefreshFlag = false
    
   // MARK: 加载数据
      func loadData(){
        
        if isLoading {
            print("正在拼命加载")
            return
        }
        
        refreshControl?.beginRefreshing()
        
        var since_id = homeStatuses?.first?.id ?? 0
        
        var max_id = 0
        
        if pullRefreshFlag{
            since_id = 0
            max_id = homeStatuses!.last!.id - 1
        }
        
        Status.loadSinaData(since_id,max_id: max_id) { (statusList, error) -> () in
            
            self.isLoading = false
            
            self.refreshControl?.endRefreshing()
            
            if error != nil{
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                return
            }
            
            if statusList == nil{
                print("没有数据")
                return
            }
            
            if since_id > 0 {
                print("下拉刷新")
                for s in statusList!{
                    print(s.text)
                }
                self.homeStatuses = statusList! + self.homeStatuses!
                print(self.homeStatuses?.count)
               
            }
            else if max_id > 0{
                print("上拉刷新")
                print("刷新了\(statusList!.count)数据")
                self.homeStatuses = self.homeStatuses! + statusList!
                self.pullRefreshFlag = false
            }
            else{
                self.homeStatuses = statusList
            }
        }
        isLoading = true
    }
    
    // MARK: tableView数据源方法
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return homeStatuses?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let status = homeStatuses![indexPath.row]
        
        let ID = StatusCell.reuserIdentifierForCell(status)
        
        let cell = tableView.dequeueReusableCellWithIdentifier(ID) as! StatusCell
        
        cell.status = status
        
        cell.photoDelegate = self
        
        if indexPath.row == homeStatuses!.count - 1{
            print("准备上拉刷新")
            pullRefreshFlag = true
            loadData()
        }
        
        
        return cell
    }
    
    // MARK: statusCell代理方法 点击图片完成跳转
    func statusCellImageDidClick(cell: StatusCell, index: Int) {
        let idxPath = tableView.indexPathForCell(cell)!
        let imageUrls = homeStatuses![(idxPath.row)].largePicURLS
        let vc = PhotoBrowserViewController(imageUrls: imageUrls!, index: index)
        //添加一个和点击的iconView 图片一样，frame一样的图片，然后再modal动画里面让其移动好已经算好frame那！
        presentView.image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(imageUrls![index].absoluteString)
        presentView.contentMode = UIViewContentMode.ScaleAspectFill
        presentView.frame = cell.screenFrame(index)
        toFrame = cell.fullScreenFrame(index)
        UIApplication.sharedApplication().keyWindow?.addSubview(presentView)
        selectedCell = cell
        
        vc.transitioningDelegate = self
        vc.modalPresentationStyle = UIModalPresentationStyle.Custom
        
        presentViewController(vc, animated: true, completion: nil)
        
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        let status = homeStatuses![indexPath.row]
        if rowHeightCache[status.id] != nil{
            return rowHeightCache[status.id]!
        }
        
        let ID = StatusCell.reuserIdentifierForCell(status)

        var cls : AnyClass = NormalStatusCell.self
        
        if ID == statusForwardReuserCellIdentifier{
            cls = ForwardStatusCell.self
        }
        
        let cell = cls.new() as! StatusCell
        
        let height = cell.rowHeight(status)
        
        rowHeightCache[status.id] = height
        
        return height
    }
    
    
    // MARK: 设置naviBar
   private func setUpNavigationBar(){
        //注意这里的逻辑
        if sharedAccount == nil{
            return
        }
//创建一个UIBarButtonItem的扩展，在扩展里面构建convinience init 方法（快速构造方法），快速创建一个item
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch", imageName_highlighted: nil)
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", imageName_highlighted: nil)
        let rightBtn = navigationItem.rightBarButtonItem?.customView as! UIButton
        rightBtn.addTarget(self, action: "showQRCodeView", forControlEvents: UIControlEvents.TouchUpInside)
        
        navigationItem.titleView = HomeTitleButton.button((sharedAccount?.name)!)
        let btn = navigationItem.titleView as! HomeTitleButton
        btn.addTarget(self, action: "titleButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
    }
    
    private func setUpTableView(){
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        tableView.registerClass(ForwardStatusCell.self, forCellReuseIdentifier: statusForwardReuserCellIdentifier)
        tableView.registerClass(NormalStatusCell.self, forCellReuseIdentifier: statusNormalReuserCellIdentifier)
    }
    
    // MARK: 跳到二维码界面
    func showQRCodeView(){
        let sb = UIStoryboard(name: "QRCode", bundle: nil)
        presentViewController(sb.instantiateInitialViewController()!, animated: true, completion: nil)
    }
    
    lazy var animator : GXPopoverAnimator = {
        return GXPopoverAnimator()
        }()
    
    func titleButtonClick(){
        let sb = UIStoryboard(name: "MyGroup", bundle: nil)
        let vc = sb.instantiateViewControllerWithIdentifier("FriendGroup")

        //设置modal动画代理
        vc.transitioningDelegate = animator
        vc.modalPresentationStyle = UIModalPresentationStyle.Custom
        animator.presentFrame = CGRectMake(view.frame.width * 0.25, 60, view.frame.width * 0.5, view.frame.height * 0.5)
        presentViewController(vc, animated: true, completion: nil)
    }

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        visitorView?.startAnimation()
//        if isLoading {
//            refreshControl?.beginRefreshing()
//        }
    }
     /// 是否在加载数据的判断，如果在加载数据就直接返回，避免网速过慢的时候重复发送相同网络请求
     private var isLoading = false
    
    /// 判断动画是present 还是dismiss
    var isPresenting = false
   /// modal动画替代视图
   lazy var presentView = UIImageView()
    /// modal到得准确位置
    var toFrame = CGRectZero
    
    var selectedCell : StatusCell?
   
}

extension HomeTableViewController : UIViewControllerTransitioningDelegate,UIViewControllerAnimatedTransitioning{
    
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresenting = true
        return self
    }
    
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresenting = false
        return self
    }
    
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        return 0.5
    }
    
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        
        if isPresenting {
            //present 动画
            let toView = transitionContext.viewForKey(UITransitionContextToViewKey)
            transitionContext.containerView()?.addSubview(toView!)
            toView?.alpha = 0
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
                self.presentView.frame = self.toFrame
                }, completion: { (_) -> Void in
                    toView?.alpha = 1
                    self.presentView.removeFromSuperview()
                    transitionContext.completeTransition(true)
            })
        }else{
            //dismiss 动画
            let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)
            
            let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! PhotoBrowserViewController
            let iv = fromVC.currentImageView()
            
            iv.transform = CGAffineTransformScale(iv.transform, (fromView?.transform.a)!, (fromView?.transform.a)!)
            iv.center = fromView!.center
            iv.contentMode = UIViewContentMode.ScaleAspectFill
            
            transitionContext.containerView()?.addSubview(iv)
            
            fromView?.removeFromSuperview()
            
            let rect = selectedCell?.screenFrame(fromVC.currentImageIndex())
            
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
                iv.frame = rect!
                }, completion: { (_) -> Void in
                    iv.removeFromSuperview()
                    transitionContext.completeTransition(true)
                    
            })
        }
    }
    

}
